package com.xujiang.myblog.ui;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.umeng.message.PushAgent;
import com.xujiang.common.ui.CPBaseActivity;
import com.xujiang.myblog.MainActivity;
import com.xujiang.myblog.R;
import com.xujiang.myblog.listener.EmptyTextChangedListener;
import com.xujiang.myblog.model.AccessToken;
import com.xujiang.myblog.model.LoginResult;
import com.xujiang.myblog.model.PreferUser;
import com.xujiang.myblog.network.retrofit.MRetrifit;
import com.xujiang.myblog.tools.CPProgressHelper;
import com.xujiang.myblog.util.Callback;
import com.xujiang.myblog.util.Callback4;
import com.xujiang.myblog.util.InputMethodUtils;
import com.xujiang.myblog.util.UIUtils;
import com.xujiang.myblog.util.ValidateUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class LoginActivity extends CPBaseActivity {

    @BindView(R.id.user_login_email)
    EditText userLoginEmail;
    @BindView(R.id.user_login_password)
    EditText userLoginPassword;
    @BindView(R.id.user_login_forget_password)
    Button userLoginForgetPassword;
    @BindView(R.id.user_login_btn)
    Button userLoginBtn;
    @BindView(R.id.user_login_register)
    Button userLoginRegister;

    private CPProgressHelper mProgressHelper;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initToolbar();
        mProgressHelper = CPProgressHelper.with(this);
        userLoginEmail.addTextChangedListener(mEmptyTextChangedListener);
        userLoginPassword.addTextChangedListener(mEmptyTextChangedListener);

    }

    EmptyTextChangedListener mEmptyTextChangedListener = new EmptyTextChangedListener(
            new Callback4.EmptyCallback<CharSequence>() {
                @Override public void onYes(CharSequence charSequence) {
                    checkSubmitEnabled();
                }

                @Override public void onNo(CharSequence charSequence) {
                    userLoginBtn.setEnabled(false);
                }
            });

    private void checkSubmitEnabled() {
        boolean empty = !TextUtils.isEmpty(userLoginPassword.getText());
        boolean empty1 = !TextUtils.isEmpty(userLoginEmail.getText());
        userLoginBtn.setEnabled(empty && empty1);
    }

    @Override protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (userLoginEmail == null || userLoginPassword == null) {
            return;
        }
        userLoginEmail.setText("");
        userLoginPassword.setText("");
    }

    public static void login(Context context) {
        login(context,null,null);
    }

    public static void login(Context context, String account, String password) {
        Bundle bundle = new Bundle();
        bundle.putString("account", account);
        bundle.putString("password", password);
        UIUtils.startActivity(context, LoginActivity.class, bundle);
    }





    private void initToolbar() {
        initToolBar();
        setTitle("登陆");
    }

    @OnClick({R.id.user_login_forget_password, R.id.user_login_btn, R.id.user_login_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.user_login_forget_password:
                UIUtils.startActivity(getActivity(), ForgetPasswordActivity.class);
                break;
            case R.id.user_login_btn:
                String mail = userLoginEmail.getText().toString();
                String pwd = userLoginPassword.getText().toString();

                try {
                    ValidateUtils.isBlank(mail,getString(R.string.valid_str_can_not_blank));
                    ValidateUtils.isEmail(mail, getString(R.string.valid_str_email_invalid));
                    ValidateUtils.lessLength(pwd, 6, getString(R.string.valid_str_pwd_longer_than_6));
                    ValidateUtils.greaterLength(pwd, 32, getString(R.string.valid_str_pwd_less_than_32));
                    ValidateUtils.isContainsLetterAndNumber(pwd,getString(R.string.valid_str_pwd_must_letter_and_number));
                } catch (Exception e) {
                    UIUtils.showToast(getApplicationContext(),e.getMessage());
                    return;
                }
                view.requestFocus(); //获取焦点
                InputMethodUtils.hideSoftInput(this);
                actionLogin(this, userLoginEmail.getText().toString(), userLoginPassword.getText().toString());



                break;
            case R.id.user_login_register:
                UIUtils.startActivity(getActivity(), RegisterActivity.class);
                break;
        }
    }

    private void actionLogin(Context context, String acc, String pwd) {
        MRetrifit.get()
                .login(context, acc, pwd, PushAgent.getInstance(this).getRegistrationId(),
                        this.<AccessToken<LoginResult>>bindToLifecycle(),
                        new Callback.EmptyCallback<AccessToken<LoginResult>>() {  //内部已经保存到本地
                            @Override public void onPreExecute() {
                                mProgressHelper.visible();
                            }

                            @Override public void onSuccess(AccessToken o) {
                                PreferUser.get().setLogin(true);
                                MainActivity.logInOut(getActivity());
                                finish();
                            }

                            @Override public void onError(Exception e) {
                                mProgressHelper.gone();
                                e.printStackTrace();
                            }
                        });
    }
}
